import 'dart:async';
import 'package:flutter/material.dart';
import 'events/theme_event.dart';
import 'common/app_color_size.dart';
import 'router.dart';
import 'common/common_ui.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MyApp> {
  StreamSubscription _themeSubscription; // 主题设置EventBus
  bool isDark; // 是否夜间模式
  
  ThemeData lightTheme = ThemeData(
      // primarySwatch: appPrimaryColor,
      brightness: Brightness.light, //设置明暗模式为暗色
      accentColor: appPrimaryColor, //(按钮）Widget前景色为黑色
      primaryColor: appPrimaryColor, //主色调为青色
      textTheme: TextTheme(body1: TextStyle(color: Colors.black87)) //设置文本颜色为红色
  );
  ThemeData darkTheme = ThemeData(
      // primarySwatch: appPrimaryColor,
      brightness: Brightness.dark, //设置明暗模式为暗色
      accentColor: appDarkPrimaryColor, //(按钮）Widget前景色为黑色
      primaryColor: appDarkPrimaryColor, //主色调为青色
      textTheme: TextTheme(body1: TextStyle(color: Colors.black87)) //设置文本颜色为红色
  );
  ThemeData currentTheme;

  @override
  void initState() {
    super.initState();
    _setTheme();
    //订阅eventbus
    _themeSubscription = eventBus.on<ThemeEvent>().listen((event) {
      //缓存主题色
      cacheTheme(event.isDark);
      setState(() {
        isDark = event.isDark;
        _setTheme();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    //取消订阅
    _themeSubscription.cancel();
  }


  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
        title: 'Flutter Demo 1',
        theme: currentTheme ??= lightTheme,
        // home: MyHomePage(title: 'Flutter Demo Home Page'),
        initialRoute: "/", //名为"/"的路由作为应用的home(首页) home和initialRoute不能同时出现
        //注册路由表
        routes: RoutePath,
    );
  }

  void _setTheme() async {
    bool isDark = await getCacheTheme();
    setState(() {
      if(isDark){
        currentTheme = darkTheme;
      }else{
        currentTheme = lightTheme;
      }
    });
  }
}
